//
//  DXPictureHolderView.swift
//  weiBoOfSwift
//
//  Created by simon on 15/12/14.
//  Copyright © 2015年 simon. All rights reserved.
//

import UIKit
import SVProgressHUD

  protocol DXPictureHolderViewDelegate : NSObjectProtocol{

    func pictureHolderViewPicturesChanged()
    
}
let reuseIdentifier:String = "DXPictureHolderCell"
class DXPictureHolderView: UICollectionView ,UICollectionViewDataSource,UICollectionViewDelegate{
   
   weak var holderViewDelegate:DXPictureHolderViewDelegate?
    
//    图片数据源
     var pictures = [UIImage]()
    
    var pictureHolderViewAddItemClickClosure:(()->())?
    
    var hasPicture:Bool{
        return pictures.count == 0 ? false : true
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        registerClass(DXPictureHolderCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        delegate = self
        dataSource = self
        
        scrollEnabled = false
        
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
//    MARK:初始化UI
    private func setUpUI(){
    backgroundColor = UIColor.whiteColor()
        self.hidden = true
    }
//    MARK:对外界调用添加图片的方法
    func addImage(image:UIImage){
        if pictures.count < 9 {
       pictures.append(image)
            
       holderViewDelegate?.pictureHolderViewPicturesChanged()
//        刷新数据
      reloadData()
        }else {
        SVProgressHUD.showErrorWithStatus("一共只能选择9张照片", maskType: SVProgressHUDMaskType.Black)
        }
         self.hidden = pictures.count==0 ? true : false
    }
    // MARK: - layoutSubViews
    override func layoutSubviews() {
        super.layoutSubviews()
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        
        let itemMargin:CGFloat = 3
         let itemWH = CGFloat( Int(self.width - 2 * itemMargin)/3 )
        
         layout.itemSize = CGSizeMake(itemWH, itemWH)
         layout.minimumLineSpacing = itemMargin
         layout.minimumInteritemSpacing = itemMargin
    }
    
    
}
//MARK: collectionView的代理方法
extension DXPictureHolderView{

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let count = (self.pictures.count == 0 || self.pictures.count == 9) ? self.pictures.count : (self.pictures.count + 1)
        return count
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let item = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! DXPictureHolderCell
        
        item.deleteIMGBtnClickCloseure = {[weak self](cell)->()in
         let seletctInpath = self?.indexPathForCell(cell)
//            logPrint(seletctInpath)
         self!.pictures.removeAtIndex(seletctInpath!.row)
           self!.holderViewDelegate?.pictureHolderViewPicturesChanged()  
         self!.reloadData()
        }
      
        item.img = (indexPath.item == pictures.count) ? nil : pictures[indexPath.item]
    return item
    }
    
    // MARK: - 添加item点击事件
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
      collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        if indexPath.item == pictures.count{
        
            pictureHolderViewAddItemClickClosure?()
        
        }
    }
}

//MARK:collectionViewCell
class DXPictureHolderCell: UICollectionViewCell {
    
    var deleteIMGBtnClickCloseure:((deleteItem:DXPictureHolderCell)->())?
    
    var img:UIImage?{
        didSet{
           
            imgView.image = img==nil ? UIImage(named: "compose_pic_add") : img
            
            if img==nil {
            imgView.image = UIImage(named: "compose_pic_add")
            imgView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
            deleteBtton.hidden = true
            }else{
             imgView.image = img
             imgView.highlightedImage = nil
             deleteBtton.hidden = false
            }
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
//            contentView.backgroundColor = radomCorlor()
        //        添加子控件
        contentView.addSubview(imgView)
        contentView.addSubview(deleteBtton)
        //        添加约束
        imgView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        deleteBtton.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(imgView).offset(2)
            make.top.equalTo(imgView).offset(-2)
        }
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK:懒加载 图片
    lazy var imgView:UIImageView = {
        let imgView = UIImageView()
        return imgView
        
    }()
    lazy var deleteBtton:UIButton = {
      let deleteBtton = UIButton()
        deleteBtton.setImage(UIImage(named:"compose_photo_close"), forState: .Normal)
        deleteBtton.addTarget(self, action: "deleteIMG", forControlEvents: .TouchUpInside)
        
        return deleteBtton
    }()
    
    // MARK: - deleteIMG删除图片按钮点击事件
    @objc private func deleteIMG(){
        
    deleteIMGBtnClickCloseure?(deleteItem: self)
        
    }
    
}












